import 'package:dio/adapter.dart';
import 'package:dio/dio.dart';
import 'package:flutter_demo/config/http_config.dart';

class HttpUtil {
  static final BaseOptions baseOptions = BaseOptions(sendTimeout: HttpConfig.timeout, baseUrl: HttpConfig.baseURL);
  static final Dio _dio = Dio(baseOptions);

  static Future<T> request<T>(String url, {String method = "get", Map<String, dynamic>? params}) async {
    (_dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (client) {
      client.badCertificateCallback = (cert, host, port) {
        return true; // 返回true强制通过
      };
    };
    // 1.单独相关的设置
    Options options = Options();
    options.method = method;

    // 2.发送网络请求
    try {
      Response response = await _dio.request<T>(url, queryParameters: params, options: options);
      return response.data;
    } on DioError catch (e) {
      throw e;
    }
  }

  static Future<T> get<T>(String url, {Map<String, dynamic>? params}) {
    return request(url, method: "get", params: params);
  }

  static Future<T> post<T>(String url, {Map<String, dynamic>? params}) {
    return request(url, method: "post", params: params);
  }

  static Future<T> put<T>(String url, {Map<String, dynamic>? params}) {
    return request(url, method: "put", params: params);
  }

  static Future<T> delete<T>(String url, {Map<String, dynamic>? params}) {
    return request(url, method: "delete", params: params);
  }
}
